/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        int res = 0;
        if (root != null){
            Deque<TreeNode> stack = new LinkedList<>();
            HashSet<TreeNode> visited = new HashSet<>();
            stack.push(root);
            res++;
            while (!stack.isEmpty()) {
                if (stack.peek().left != null && !visited.contains(stack.peek().left)){
                    stack.push(stack.peek().left);
                    visited.add(stack.peek());
                    res = Math.max(res, stack.size());
                } else if (stack.peek().right != null && !visited.contains(stack.peek().right)){
                    stack.push(stack.peek().right);
                    visited.add(stack.peek());
                    res = Math.max(res, stack.size());
                } else {
                    stack.pop();
                }
            }
        }
        return res;
    }

    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    }
}